package com.gitee.yannzh.rune.support.crud.model;

import com.gitee.yannzh.rune.support.crud.annotation.Dict;
import com.gitee.yannzh.rune.support.crud.annotation.Form;
import com.gitee.yannzh.rune.support.crud.annotation.ViewField;
import com.gitee.yannzh.rune.support.crud.constants.ViewType;
import com.gitee.yannzh.rune.support.crud.util.TypeUtil;
import lombok.Data;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author Yann
 * @date 2025/4/18 14:08
 * @description
 * @since 1.0.0
 */
@Data
public class ViewFieldModel {
    private String fieldName;

    private String rawFieldName;

    private String title;

    private String desc;

    private ViewType type;

    private Boolean search;

    private Integer order;

    private Boolean show;

    private ViewForm form;

    private ViewForm addForm;

    private ViewForm editForm;

    private ViewDict dict;

    public static ViewFieldModel ToModelBean(Class<?> type, String name, ViewField anno) {

        ViewFieldModel fieldModel = new ViewFieldModel();
        fieldModel.rawFieldName = name;
        fieldModel.fieldName = StringUtils.isNotEmpty(anno.field()) ? anno.field() : name;
        fieldModel.title = anno.title();
        fieldModel.type = anno.type();
        fieldModel.search = anno.search().value();
        fieldModel.order = anno.order();
        fieldModel.show = anno.show();
        fieldModel.desc = anno.desc();

        ViewType t = anno.type();
        if (t == ViewType.AUTO) {
            fieldModel.type = TypeUtil.mappingType(type.getSimpleName());
        }
        Form form = anno.form();
        ViewForm vf = new ViewForm();
        vf.setTitle(StringUtils.isNotEmpty(form.title()) ? form.title() : anno.title());
        vf.setDesc(StringUtils.isNotEmpty(form.desc()) ? form.desc() : anno.desc());
        vf.setShow(form.show());
        vf.setReadonly(form.readonly());
        vf.setOrder(form.order());
        vf.setType(form.type() != ViewType.AUTO ? form.type() : fieldModel.type);
        fieldModel.form = vf;

        Dict dict = anno.dict();
        ViewDict dc = new ViewDict();
        if (StringUtils.isNotEmpty(dict.code())) {
            dc.setCode(dict.code());
        }
        if (ArrayUtils.isNotEmpty(dict.data())) {
            dc.setData(Arrays.stream(dict.data()).map(e -> new DictData(e.value(), e.label())).collect(Collectors.toList()));
        }
        dc.setUrl(dict.url());
        fieldModel.dict = dc;
        return fieldModel;
    }

}
